package com.dq.service;

import com.dq.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserDetailsService {

    @Autowired
    UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String id) throws UsernameNotFoundException {

        com.dq.pojo.User user = userMapper.getUserById(id);

        if (user==null) {
            throw new UsernameNotFoundException(id);
        }
        // 封装成 Spring security 定义的 User 对象

        List<GrantedAuthority> auths= AuthorityUtils.commaSeparatedStringToAuthorityList(user.getRole());
        return new User(user.getId(),new BCryptPasswordEncoder().encode(user.getPwd()),auths);
    }

    }

